package com.cyys.common.redis.mybatis;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
 
public class MybatisRedisCache implements Cache {
	
	private static RedisTemplate<String, Object> redisTemplate;
	
    private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);
 
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
 
    private String id;
 
    public MybatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);
        this.id = id;
    }
 
    @Override
    public String getId() {
        return this.id;
    }
 
    @Override
    public int getSize() {
    	return 0;
        //return Integer.valueOf(redisClient.dbSize().toString());
    }
 
    @Override
    public void putObject(Object key, Object value) {
    	redisTemplate.opsForValue().set(key.toString(),value);
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);
        //redisClient.set(MybatisSerializeUtil.serialize(key.toString()), MybatisSerializeUtil.serialize(value));
    }
 
    @Override
    public Object getObject(Object key) {
    	Object value = redisTemplate.opsForValue().get(key.toString());
    	logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);
    	return value;
        //Object value = MybatisSerializeUtil.unserialize(redisClient.get(MybatisSerializeUtil.serialize(key.toString())));
    }
 
    @Override
    public Object removeObject(Object key) {
        redisTemplate.delete(key.toString());
        return "1";
        //return redisClient.expire(MybatisSerializeUtil.serialize(key.toString()), 0);
    }
 
    @Override
    public void clear() {
    	//redisUtil.flushDB();
    }
 
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

	public static void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		MybatisRedisCache.redisTemplate = redisTemplate;
	}
 
}   